// 游戏配置
const config = {
    baseSpeed: 100,
    speedMultiplier: 0.8,
    levelScoreRequirement: 100,
    difficultySettings: {
        easy: { speedMultiplier: 1, scoreMultiplier: 1, obstacleCount: 0 },
        medium: { speedMultiplier: 1.2, scoreMultiplier: 1.5, obstacleCount: 3 },
        hard: { speedMultiplier: 1.5, scoreMultiplier: 2, obstacleCount: 5 }
    },
    gameModesSettings: {
        classic: { name: "经典模式", description: "传统贪吃蛇玩法" },
        timeAttack: { name: "限时模式", description: "在限定时间内获得最高分", timeLimit: 180 },
        survival: { name: "生存模式", description: "障碍物会随机移动" }
    },
    specialFoods: {
        golden: { color: '#FFD700', points: 5, chance: 0.1, effect: 'doublePoints' },
        speed: { color: '#00FF00', points: 2, chance: 0.15, effect: 'speedBoost' },
        ghost: { color: '#87CEEB', points: 3, chance: 0.1, effect: 'ghostMode' }
    },
    powerUps: {
        shield: { duration: 5000, color: '#4169E1' },
        slowMotion: { duration: 3000, factor: 0.5 },
        magnet: { duration: 4000, radius: 50 }
    },
    achievements: [
        { id: 'score100', name: '初级玩家', requirement: 'score >= 100' },
        { id: 'score500', name: '中级玩家', requirement: 'score >= 500' },
        { id: 'score1000', name: '高级玩家', requirement: 'score >= 1000' },
        { id: 'level5', name: '闯关专家', requirement: 'level >= 5' }
    ]
};

// 游戏状态
let snake = [{ x: 200, y: 200 }];
let direction = { x: 0, y: 0 };
let food = { x: 0, y: 0 };
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;
let currentLevel = 1;
let gameInterval;
let gameStarted = false;
let gameOver = false;
let currentSpeed = config.baseSpeed;
let obstacles = [];
let specialFood = null;
let currentGameMode = 'classic';
let activePowerUps = [];
let achievements = new Set();
let timeLeft = 0;
let ghostMode = false;

// 更新显示
highScoreElement.textContent = highScore;
updateNextLevelTarget();

// 速度控制
speedRange.addEventListener('input', function() {
    speedValue.textContent = this.value;
    if (gameStarted) {
        updateGameSpeed();
    }
});

// 难度选择
difficultySelect.addEventListener('change', function() {
    if (gameStarted) {
        updateGameSpeed();
    }
});

function updateGameSpeed() {
    const speedFactor = 11 - speedRange.value; // 反转速度值（1是最快，10是最慢）
    const difficultyFactor = config.difficultySettings[difficultySelect.value].speedMultiplier;
    const levelFactor = Math.pow(config.speedMultiplier, currentLevel - 1);
    
    currentSpeed = config.baseSpeed * speedFactor * difficultyFactor * levelFactor;
    
    if (gameStarted) {
        clearInterval(gameInterval);
        gameInterval = setInterval(() => {
            update();
            draw();
        }, currentSpeed);
    }
}

function updateNextLevelTarget() {
    const nextLevelScore = currentLevel * config.levelScoreRequirement;
    nextLevelTargetElement.textContent = nextLevelScore - score;
}

function checkLevelUp() {
    const nextLevelScore = currentLevel * config.levelScoreRequirement;
    if (score >= nextLevelScore) {
        currentLevel++;
        currentLevelElement.textContent = currentLevel;
        updateNextLevelTarget();
        updateGameSpeed();
        
        // 显示关卡提示
        showLevelUpMessage();
    }
}

function showLevelUpMessage() {
    const levelUpText = `Level ${currentLevel}!`;
    ctx.fillStyle = 'rgba(76, 175, 80, 0.8)';
    ctx.font = '40px "Press Start 2P"';
    ctx.fillText(levelUpText, canvas.width/2 - 100, canvas.height/2);
}

function initGame() {
    // 初始化障碍物
    obstacles = [];
    const obstacleCount = config.difficultySettings[difficultySelect.value].obstacleCount;
    for (let i = 0; i < obstacleCount; i++) {
        spawnObstacle();
    }
    
    // 初始化特殊食物
    specialFood = null;
    
    // 初始化时间（用于限时模式）
    if (currentGameMode === 'timeAttack') {
        timeLeft = config.gameModesSettings.timeAttack.timeLimit;
    }
}

function spawnObstacle() {
    const obstacle = {
        x: Math.floor(Math.random() * (canvas.width / 10)) * 10,
        y: Math.floor(Math.random() * (canvas.height / 10)) * 10
    };
    
    // 确保障碍物不会出现在蛇身上或食物上
    while (
        snake.some(segment => segment.x === obstacle.x && segment.y === obstacle.y) ||
        (food.x === obstacle.x && food.y === obstacle.y) ||
        obstacles.some(obs => obs.x === obstacle.x && obs.y === obstacle.y)
    ) {
        obstacle.x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
        obstacle.y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
    }
    
    obstacles.push(obstacle);
}

function spawnSpecialFood() {
    const random = Math.random();
    let cumulative = 0;
    
    for (const [type, food] of Object.entries(config.specialFoods)) {
        cumulative += food.chance;
        if (random <= cumulative) {
            specialFood = {
                x: Math.floor(Math.random() * (canvas.width / 10)) * 10,
                y: Math.floor(Math.random() * (canvas.height / 10)) * 10,
                type: type
            };
            break;
        }
    }
}

function checkCollision(head) {
    // 检查是否撞墙
    if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
        return !ghostMode; // 幽灵模式下可以穿墙
    }
    
    // 检查是否撞到自己
    if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        return true;
    }
    
    // 检查是否撞到障碍物
    if (!ghostMode && obstacles.some(obstacle => obstacle.x === head.x && obstacle.y === head.y)) {
        return true;
    }
    
    return false;
}

function update() {
    if (!gameStarted || gameOver) return;
    
    const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
    
    // 幽灵模式下的穿墙处理
    if (ghostMode) {
        if (head.x < 0) head.x = canvas.width - 10;
        if (head.x >= canvas.width) head.x = 0;
        if (head.y < 0) head.y = canvas.height - 10;
        if (head.y >= canvas.height) head.y = 0;
    }
    
    // 检查碰撞
    if (checkCollision(head)) {
        gameOver = true;
        clearInterval(gameInterval);
        return;
    }
    
    snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        const difficultyMultiplier = config.difficultySettings[difficultySelect.value].scoreMultiplier;
        score += 10 * difficultyMultiplier;
        spawnFood();
        
        // 有机会生成特殊食物
        if (!specialFood && Math.random() < 0.3) {
            spawnSpecialFood();
        }
    } else if (specialFood && head.x === specialFood.x && head.y === specialFood.y) {
        // 处理特殊食物效果
        handleSpecialFood();
    } else {
        snake.pop();
    }
    
    // 更新分数和等级
    scoreElement.textContent = score;
    if (score > highScore) {
        highScore = score;
        highScoreElement.textContent = highScore;
        localStorage.setItem('snakeHighScore', highScore);
    }
    
    checkLevelUp();
    checkAchievements();
    updatePowerUps();
    
    // 生存模式下随机移动障碍物
    if (currentGameMode === 'survival' && Math.random() < 0.02) {
        moveRandomObstacle();
    }
    
    // 限时模式倒计时
    if (currentGameMode === 'timeAttack') {
        timeLeft--;
        if (timeLeft <= 0) {
            gameOver = true;
            clearInterval(gameInterval);
        }
    }
}

function handleSpecialFood() {
    const foodConfig = config.specialFoods[specialFood.type];
    score += foodConfig.points * config.difficultySettings[difficultySelect.value].scoreMultiplier;
    
    // 应用特殊效果
    switch (foodConfig.effect) {
        case 'doublePoints':
            activePowerUps.push({
                type: 'doublePoints',
                duration: 5000,
                startTime: Date.now()
            });
            break;
        case 'speedBoost':
            activePowerUps.push({
                type: 'speedBoost',
                duration: 3000,
                startTime: Date.now()
            });
            updateGameSpeed();
            break;
        case 'ghostMode':
            ghostMode = true;
            setTimeout(() => {
                ghostMode = false;
            }, 5000);
            break;
    }
    
    specialFood = null;
}

function updatePowerUps() {
    const currentTime = Date.now();
    activePowerUps = activePowerUps.filter(powerUp => {
        return currentTime - powerUp.startTime < powerUp.duration;
    });
}

function moveRandomObstacle() {
    if (obstacles.length > 0) {
        const obstacle = obstacles[Math.floor(Math.random() * obstacles.length)];
        const directions = [
            { x: 10, y: 0 },
            { x: -10, y: 0 },
            { x: 0, y: 10 },
            { x: 0, y: -10 }
        ];
        
        const newPos = {
            x: obstacle.x + directions[Math.floor(Math.random() * 4)].x,
            y: obstacle.y + directions[Math.floor(Math.random() * 4)].y
        };
        
        // 确保新位置有效
        if (
            newPos.x >= 0 && newPos.x < canvas.width &&
            newPos.y >= 0 && newPos.y < canvas.height &&
            !snake.some(segment => segment.x === newPos.x && segment.y === newPos.y)
        ) {
            obstacle.x = newPos.x;
            obstacle.y = newPos.y;
        }
    }
}

function checkAchievements() {
    config.achievements.forEach(achievement => {
        if (!achievements.has(achievement.id)) {
            // 评估成就条件
            const condition = achievement.requirement
                .replace('score', score)
                .replace('level', currentLevel);
            
            if (eval(condition)) {
                achievements.add(achievement.id);
                showAchievementMessage(achievement.name);
            }
        }
    });
}

function showAchievementMessage(achievementName) {
    const message = `成就解锁：${achievementName}！`;
    ctx.fillStyle = 'rgba(255, 215, 0, 0.8)';
    ctx.font = '20px "Press Start 2P"';
    ctx.fillText(message, canvas.width/2 - 150, 50);
}

function draw() {
    // 清空画布
    ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格
    drawGrid();
    
    // 绘制障碍物
    drawObstacles();
    
    // 绘制蛇和食物
    drawSnake();
    drawFood();
    
    // 绘制特殊食物
    if (specialFood) {
        drawSpecialFood();
    }
    
    // 绘制活动状态
    drawActiveEffects();
    
    // 如果是限时模式，显示剩余时间
    if (currentGameMode === 'timeAttack') {
        drawTimeLeft();
    }
    
    // 如果游戏结束，显示游戏结束文字
    if (gameOver) {
        ctx.fillStyle = 'rgba(255, 0, 0, 0.7)';
        ctx.font = '30px "Press Start 2P"';
        ctx.fillText('游戏结束!', canvas.width/2 - 100, canvas.height/2);
    }
}

function drawObstacles() {
    ctx.fillStyle = '#FF4444';
    obstacles.forEach(obstacle => {
        ctx.fillRect(obstacle.x, obstacle.y, 10, 10);
    });
}

function drawSpecialFood() {
    const foodConfig = config.specialFoods[specialFood.type];
    ctx.fillStyle = foodConfig.color;
    ctx.beginPath();
    ctx.arc(specialFood.x + 5, specialFood.y + 5, 5, 0, Math.PI * 2);
    ctx.fill();
    
    // 添加闪烁效果
    ctx.shadowColor = foodConfig.color;
    ctx.shadowBlur = 15;
    ctx.fill();
    ctx.shadowBlur = 0;
}

function drawActiveEffects() {
    let y = 70;
    activePowerUps.forEach(powerUp => {
        const timeLeft = Math.ceil((powerUp.duration - (Date.now() - powerUp.startTime)) / 1000);
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.font = '12px Arial';
        ctx.fillText(`${powerUp.type}: ${timeLeft}s`, 10, y);
        y += 20;
    });
    
    if (ghostMode) {
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.font = '12px Arial';
        ctx.fillText('幽灵模式', 10, y);
    }
}

function drawTimeLeft() {
    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
    ctx.font = '20px Arial';
    ctx.fillText(`时间: ${Math.ceil(timeLeft)}s`, canvas.width - 120, 30);
}

// 事件监听
document.addEventListener('keydown', changeDirection);
startBtn.addEventListener('click', startGame);
restartBtn.addEventListener('click', restartGame);

// 初始化游戏
initGame();
spawnFood();
draw();
